package com.campos.collection;
import android.app.Activity;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Binder;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import java.text.SimpleDateFormat;
import java.util.Date;

public class GPSService extends Service {

    private static GPSService __instance = null;
    public static GPSService getInstance(){
        return __instance;
    }
    // 2000ms
    private static final long minTime = 1000;

    // 最小变更距离 10m
    private static final float minDistance = 0.0f;

    String tag = this.toString();

    private LocationManager locationManager;

    private LocationListener locationListener;

    private final IBinder mBinder = new GPSServiceBinder();

    public void startService() {
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        locationListener = new GPSServiceListener();
        try{
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, minTime, minDistance,locationListener);
        }
        catch (SecurityException se){
            Log.v(tag, se.getMessage());
        }
        __instance = this;
    }

    public void endService() {
        if (locationManager != null && locationListener != null) {
            locationManager.removeUpdates(locationListener);
        }
        __instance = null;
    }

    @Override
    public IBinder onBind(Intent arg0) {
        // TODO Auto-generated method stub
        return mBinder;
    }

    @Override
    public void onCreate() {
        //
        startService();
        Log.v(tag, "GPSService Started.");
    }

    @Override
    public void onDestroy() {
        endService();
        Log.v(tag, "GPSService Ended.");

    }

    public class GPSServiceBinder extends Binder {
        GPSService getService() {
            return GPSService.this;
        }
    }

    public void addGPSListener(LocationListener li){
        try{
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, minTime, minDistance,li);
        }
        catch (SecurityException se){
            Log.v(tag, se.getMessage());
        }
    }

    private static class GPSServiceListener implements LocationListener {
        String filename = "";
        GPSServiceListener(){
        }

        @Override
        public void onLocationChanged(Location location) {//定位改变监听
            //writeGPSInfo(location);
        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {//定位状态监听

        }

        @Override
        public void onProviderEnabled(String provider) {//定位状态可用监听

        }

        @Override
        public void onProviderDisabled(String provider) {//定位状态不可用监听

        }
    }

}